import wepy from 'wepy'

export default class Order extends wepy.mixin {
  data = {
    // 收货地址
    addressInfo: null,
    // 商品列表
    cart: [],
    // 判断是否成功还是失败
    islogin: false
  }

  onLoad () {
    // 在订单页面加载期间，读取本地存储数据，对 addressInfo 赋值
    this.addressInfo = wepy.getStorageSync('address') || null
    // 从购物车列表中取到被勾选的商品列表
    const newArr = this.$parent.globalData.cart.filter(item => item.isCheck)
    this.cart = newArr
  }

  computed = {
    isHaveAddress () {
      if (this.addressInfo === null) {
        return false
      }

      return true
    },

    addressStr () {
      if (this.addressInfo === null) {
        return ''
      }

      const { provinceName, cityName, countyName, detailInfo } = this.addressInfo
      return provinceName + cityName + countyName + detailInfo
    },

    amount () {
      var allPrice = 0

      this.cart.forEach(item => {
        allPrice += item.count * item.price
      })

      return allPrice * 100
    }
  }

  methods = {
    // 订单提交
    async onSubmit () {
      // 判断收货地址是否为空
      if (this.addressInfo === null) {
        return wepy.baseToast('请选择收货地址')
      }
      // 判断金额是否小于 0
      if (this.amount <= 0) {
        return wepy.baseToast('订单金额出错')
      }

      // 1、创建订单
      const {data: createResult } = await wepy.post('/my/orders/create', {
        // 这个价格，在课程中是写死的，但是在实际开发中，一定需要是真正价格
        order_price: '0.01',
        // 需要是拼接好的收获地址
        consignee_addr: this.addressStr,
        order_detail: JSON.stringify(this.cart),
        goods: this.cart.map(item => {
          return {
            'goods_id': item.id,
            'goods_number': item.count,
            'goods_price': item.price
          }
        })
      })

      if (createResult.meta.status !== 200) {
        return wepy.baseToast('订单创建失败')
      }
      const orderInfo = createResult.message
     
      // 2、生成预支付订单
      const { data: orderResult } = await wepy.post('/my/orders/req_unifiedorder', {
        order_number: orderInfo.order_number
      })

      if (createResult.meta.status !== 200) {
        return wepy.baseToast('订单创建失败')
      }

      // 3、调用微信支付 API
      const payResult = await wx.requestPayment(orderResult.message.pay).catch(err => err)

      if (payResult.errMsg === 'requestPayment:fail cancel') {
        return wepy.baseToast('您已取消支付！')
      }

      // 4、支付成功的处理
      const { data: payCheckResult } = await wepy.post('/my/orders/chkOrder', {
        order_number: orderInfo.order_number
      })

      if (payCheckResult.meta.status !== 200) {
        return wepy.baseToast('支付失败！')
      }

      wepy.showToast({
        title: '支付成功！'
      })

      wepy.navigateTo({
        url: '/pages/orderlist'
      })

      console.log(payCheckResult)
    },

    // 获取用户信息
    async getUserInfo (userInfo) {
      // 1、获取用户信息
      if (userInfo.detail.errMsg !== 'getUserInfo:ok') {
        return wepy.baseToast('获取用户信息失败！')
      }
      // console.log(userInfo)

      // 2、获取用户登录凭证
      const loginRes = await wepy.login()
      if (loginRes.errMsg !== 'login:ok') {
        return wepy.baseToast('微信登录失败！')
      }
      // console.log(loginRes)

      // 3、拼接登录的参数
      const loginParams = {
        code: loginRes.code,
        encryptedData: userInfo.detail.encryptedData,
        iv: userInfo.detail.iv,
        rawData: userInfo.detail.rawData,
        signature: userInfo.detail.signature
      }

      console.log(loginParams)
      // 4、发起登录请求
      const { data: res } = await wepy.post('/users/wxlogin', loginParams)

      if (res.meta.status !== 200) {
        return wepy.baseToast('登录失败')
      }

      wepy.setStorageSync('token', res.message.token)
      this.islogin = true
      this.$apply()
      console.log(res)
    },
    // 获取收货地址
    async chooseAddress () {
      const res = await wepy.chooseAddress().catch(err => err)

      if (res.errMsg !== 'chooseAddress:ok') {
        return wepy.baseToast('收货地址获取失败 ！')
      }

      this.addressInfo = res
      wepy.setStorageSync('address', res)
      this.$apply()
    }
  }
}
